import {
		Debounce
	} from '@/common/utils/lib/tools'
import wait from '../utils/wait.js'
export const loadlistMixin = {
	data() {
		return {
			list:[],
			page:1,
			limit:10,
			last_page:99,
			loadStatus: 'loadmore',
			requestArray:[],
			load_debounce:Debounce(()=>this.load(),300),
			loadCount:0
		}
	}, 
	mounted() {
		this.init()
	},
	onShow(){
		this.onShow() //作为组件调用的时候给父组件的方法
	},
	onReachBottom() {
		if(this.loadStatus != 'nomore' && this.loadCount>=1){
			this.loadloadmore()
		}
	},
	async onPullDownRefresh() {
		await this.init()
		uni.stopPullDownRefresh()
	},
	computed:{
		isloading() {
			return (this.loadStatus == 'loading');
		},
		noData(){
			return this.loadCount==1&& this.list && this.list.length==0 && !this.isloading
		},
		isEmpty(){
			return this.noData
		}
	},
	methods: {
		onShow(){
			if(this.loadCount>0)this.load(this.page*this.limit)
			
		},
        async onPullDownRefresh(){
            await this.init()
        },
        async onReachBottom(){
            if(this.loadStatus != 'nomore' && this.loadCount>=1){
                await this.loadloadmore()
            }
        },
		isLast(i){
			return i>=this.list.length-1
		},
		loadloadmore(){
			this.page++;
			this.load_debounce()
		},
		async beforeInit(){},
		async init(){
			this.page = 1
			this.loadCount=0
			this.last_page = 99
			this.list = []
			this.loadStatus='loadmore'
			await this.beforeInit()
			await this.load_debounce()
			this.afterInit()
		},
		afterInit(){},
		loadApi(data){
			return new Promise();
		},
		
		load(i){
			if(this.loadStatus == 'loading')return;
			
			// refresh current page
			if(typeof i == 'number' && i > -1) {
				let page = Math.floor(i / this.limit)
				let next = page + 1;
				this.list.splice(next*this.limit,999)
				this.page = page
			}
			
			
			this.loadStatus = 'loading'
			return this.loadApi({pageNum:this.page,pageSize:this.limit}).then((res)=> wait.sec(100,res)).then(({data})=>{

				this.loadCount++;
				if(data==null){
					this.loadStatus = "nomore"
					return;
				}
				let {current_page,rows:list=[],total_page:last_page=0,length:per_page,total=0}=data || {};
				this.last_page = last_page;
				if(per_page==undefined)per_page = this.limit
				if(current_page==undefined)current_page = this.page
				
				
				
				if(list.length < Number(per_page) || list.length == 0 || this.page == last_page){
					this.loadStatus = "nomore"
				}else{
					this.loadStatus = "loadmore"
				}
				// list = [1,2,3,1,1,2,3];
				this.list.splice((current_page-1)* per_page,per_page,...list)
				if(this.list.length >= total){
					this.loadStatus = "nomore"
				}
				uni.stopPullDownRefresh()
			}).catch(err=>{
				uni.stopPullDownRefresh()
				this.loadStatus = 'loadmore'
				throw err
			})
		}
	}
}

export default loadlistMixin